# -*- encoding: utf-8 -*-
'''
@File    :   sendmail.py    
@Contact :   ypy02784@163.com
@License :   (C)Copyright 2019-2020, ypy

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2020/4/3 11:01   ypy      1.0         None
'''

import smtplib
# 发送字符串的邮件
from email.mime.text import MIMEText
# 处理多种形态的邮件主体我们需要 MIMEMultipart 类
from email.mime.multipart import MIMEMultipart
# 处理图片需要 MIMEImage 类
from email.mime.image import MIMEImage
# 处理附件，如doc.xls等文件
from email.mime.application import MIMEApplication


# dxmbdjqmqhotcafb   20307103授权码
# nuzbwavmfmmkbhaa   20331623授权码

def send_mail(msg_from=None, passwd=None, msg_to=None, text_content=None):
    # 设置服务器所需信息
    # msg_from = '20331623@qq.com'  # 邮件发送方邮箱地址
    # passwd = 'nuzbwavmfmmkbhaa'  # 密码(部分邮箱为授权码)
    msg_from = 'ypy02784@163.com'  # 邮件发送方邮箱地址
    passwd = 'ypy02784'  # 密码(部分邮箱为授权码)
    msg_to = ['20307103@qq.com']  # 邮件接受方邮箱地址，注意需要[]包裹，这意味着你可以写多个邮件地址群发

    # 设置email信息
    # ---------------------------发送字符串的邮件-----------------------------
    # 邮件内容设置
    message = MIMEText('hello,ziqiiii', 'plain', 'utf-8')
    # 邮件主题
    message['Subject'] = 'ziqiiii test email'
    # 发送方信息
    message['From'] = msg_from
    # 接受方信息
    message['To'] = msg_to[0]
    # ---------------------------------------------------------------------

    # 登录并发送邮件
    try:
        server = smtplib.SMTP('smtp.163.com')  # qq邮箱服务器地址，端口默认为25
        # server = smtplib.SMTP_SSL("smtp.qq.com", 465)
        server.login(msg_from, passwd)
        server.sendmail(msg_from, msg_to, message.as_string())
        print('success')
        server.quit()

    except smtplib.SMTPException as e:
        print('error', e)  # 打印错误


# 写成了一个通用的函数接口，带附件
def sen_email_file(msg_from=None, passwd=None, msg_to=None, text_content=None, file_path=None):
    msg_from = 'ypy02784@163.com'  # 发送方邮箱
    passwd = 'ypy02784'  # 填入发送方邮箱的授权码（就是刚刚你拿到的那个授权码）
    msg_to = '20307103@qq.com'  # 收件人邮箱

    msg = MIMEMultipart()

    subject = "Test My Email"  # 主题
    text_content = "你好啊，你猜这是谁发的邮件"
    text = MIMEText(text_content)
    msg.attach(text)

    file_path = 'C:/1.txt'  # 如果需要添加附件，就给定路径
    if file_path:  # 最开始的函数参数我默认设置了None ，想添加附件，自行更改一下就好
        docFile = file_path
        docApart = MIMEApplication(open(docFile, 'rb').read())
        docApart.add_header('Content-Disposition', 'attachment', filename=docFile)
        msg.attach(docApart)

    msg['Subject'] = subject
    msg['From'] = msg_from
    msg['To'] = msg_to

    try:
        s = smtplib.SMTP_SSL("smtp.163.com", 465)
        s.login(msg_from, passwd)
        s.sendmail(msg_from, msg_to, msg.as_string())
        print("发送成功")
    except:
        print("发送失败")
    finally:
        s.quit()


sen_email_file()